import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/model/news.dart';
import 'package:flutter_app/style/color.dart';
import 'package:loading_animations/loading_animations.dart';
import 'package:webview_flutter/webview_flutter.dart';

class NewsDetails extends StatefulWidget {
  final News news;

  NewsDetails(this.news, {Key key}) : super(key: key);
  @override
  _NewsDetailsState createState() => _NewsDetailsState();
}

class _NewsDetailsState extends State<NewsDetails> {
  WebViewController _controller;
  bool _isPageFinished = false;
  double _webViewHeight = 200;

  // 注册js回调
  JavascriptChannel _invokeJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Invoke',
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);
          var webHeight = double.parse(message.message);
          if (webHeight != null) {
            setState(() {
              _webViewHeight = webHeight;
            });
          }
        });
  }

  _buildWebView() {
    return WebView(
      initialUrl: 'about:blank',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
    );
  }

  _loadHtmlFromAssets() async {
    _controller.loadUrl(Uri.dataFromString(
            """
       <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .content-picture{
            display: inline-block; width: 100%; max-width: 100%; height: auto;
        }
    </style>
</head>
<body>
""" +
                widget.news.text +
                """
</body>
</html>
        """,
            mimeType: 'text/html',
            encoding: Encoding.getByName('utf-8'))
        .toString());
  }

  //后退到上一页
  _backToPreviousPage() {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: m_color.black,
          leading: IconButton(
            padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
            alignment: Alignment.centerRight,
            icon: (Icon(Icons.arrow_back)),
            onPressed: _backToPreviousPage,
          ),
        ),
        //body占屏幕的大部分
        body: _buildWebView());
  }
}
